package com.topnav.mc.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.js.lib.cache.SysCache;
import com.js.lib.result.Result;
import com.js.lib.utils.ResultUtil;
import com.topnav.mc.admin.entity.Organization;
import com.topnav.mc.admin.entity.User;
import com.topnav.mc.admin.entity.enums.EnumLogType;
import com.topnav.mc.admin.entity.enums.EnumOperateFunction;
import com.topnav.mc.admin.security.CustomLoginSuccess;
import com.topnav.mc.admin.security.PermissionGrade;
import com.topnav.mc.admin.security.config.JwtProperties;
import com.topnav.mc.admin.service.IOperateLogService;
import com.topnav.mc.admin.service.IOrganizationService;
import com.topnav.mc.admin.service.IUserService;
import com.topnav.mc.common.Constant;
import com.topnav.mc.exception.ExceptionMsg;
import com.topnav.mc.uitls.ErrorResultUtil;
import com.topnav.mc.uitls.PermissionGradeUtil;
import com.topnav.mc.uitls.ResultErrorUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 认证
 */
@Slf4j
@CrossOrigin
@RestController
/*@RequestMapping(value = "/auth",
        consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE)*/
@RequestMapping(value = "/auth")
public class AuthController {
    @Autowired
    private SysCache sysCache;
    @Resource
    private JwtProperties jwtProperties;
    @Autowired
    private IUserService userService;
    @Autowired
    private IOrganizationService organizationService;
    @Autowired
    private CustomLoginSuccess customLoginSuccess;
    @Autowired
    private PermissionGradeUtil permissionGradeUtil;
    @Autowired
    private IOperateLogService operateLogService;

    /**
     * 切换单位登录
     * @param orgCode
     * @return
     */
    @PostMapping("/login/chanage/org")
    public Result login(String orgCode) {
        /** 更新User 的 loginOrgId*/
        PermissionGrade permissionGrade = permissionGradeUtil.getPmGradeCheck();

        String token = MDC.get(Constant.MDC_TOEKN);
        QueryWrapper<Organization> wrapper = new QueryWrapper<Organization>().eq("code",orgCode);
        Organization organization = organizationService.getOne(wrapper,false);

        LambdaUpdateWrapper<User> wrapper1 = new LambdaUpdateWrapper();
        wrapper1.set(User::getLoginOrgId,organization.getId());
        wrapper1.eq(User::getId,permissionGrade.getUserId());
        userService.update(wrapper1);
/*        User user = userService.getById(permissionGrade.getUserId());
        User user1 = new User();
        user1.setId(user.getId());
        user1.setLoginOrgId(organization.getId());
        userService.updateById(user1);*/

        /** 取得 登录成功后 数据并返回 */
   /*     Map<String,Object> resultMap = new HashMap<String,Object>();
        //resultMap.put("fullName",user.getLoginName() + "->" + organization.getShortName());
        resultMap.put("organizations",;*/
        return Result.ok(customLoginSuccess.afterLoginSuccess(permissionGrade.getUserName(),token));
    }
    /**
     * 用了Springsecurity 这个接口目录不用
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        String loginName = user.getLoginName();
        String password = user.getPassword();

        if (StringUtils.isEmpty(loginName))
            return ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_EMPTY_ACCOUNT);
        if (StringUtils.isEmpty(password))
            return ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_EMPTY_PASSWORD);

        Map<String, String> map = new HashMap<>();
        //map.put("token", uid + "_" + token);
        map.put("token", "123_123" );
        //UserUtils.getInstance().set(uid, token);
        return Result.ok(map);
    }

    // 退出
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request,String token) {

        operateLogService.saveLog(EnumLogType.LOGOUT, EnumOperateFunction.SYSTEM);

        if (StringUtils.isEmpty(token)){
            token = request.getHeader(jwtProperties.getHeader());
            if (StringUtils.isEmpty(token)){
                token = request.getParameter(jwtProperties.getHeader());
            }
        }


        /** 删除 权限 级别的记录*/
        if (!StringUtils.isEmpty(token)) {
            permissionGradeUtil.removePmGrade(token);
        }else{
            //TOKEN 参数必须提供
            return ResultErrorUtil.byExceptionMsg(ExceptionMsg.ERROR_PARAM_TOKEN_NOT_PROVIDED);
        }
        /**
         * 处理sse
         */

        return Result.ok("注销成功");
    }



}
